package org.agilelang.editor.view.tree;

/*
 AgileLang - A fourth generation language(http://www.agilelang.org).

 Copyright (C) 2013 Roderick Cusirramos (roderick20@hotmail.com)

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import org.agilelang.editor.tool.Util;

public class PopupTree implements ActionListener {

    ViewTree tree;
    JPopupMenu popup;
    Point loc;
    private MouseListener ma = new MouseAdapter() {

        private void checkForPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                loc = e.getPoint();
                TreePath path = tree.getPathForLocation(loc.x, loc.y);
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                String texto = (String) node.toString();
                File directorio = new File(texto);
                if (directorio.isDirectory()) {
                    addPopupDirectory();
                } else {
                    addPopupFile();
                }
                popup.show(tree, loc.x, loc.y);
            }
        }

        public void mousePressed(MouseEvent e) {
            checkForPopup(e);
        }

        public void mouseReleased(MouseEvent e) {
            checkForPopup(e);
        }

        public void mouseClicked(MouseEvent e) {
            checkForPopup(e);
        }
    };

    public PopupTree(ViewTree tree, JPopupMenu popup) {

        this.tree = tree;
        this.popup = popup;
        tree.addMouseListener(ma);
    }

    public void addPopupDirectory() {

        this.popup.removeAll();

        JMenuItem menuItem = new JMenuItem("New Folder", new ImageIcon(Util.getIconImage("fgl/editor/resources/img16/folder.png")));
        menuItem.setActionCommand("NewFolder");
        menuItem.addActionListener(this);
        this.popup.add(menuItem);
        this.popup.addSeparator();

        JMenu submenu = new JMenu("New File");

        menuItem = new JMenuItem("Agile", new ImageIcon(Util.getIconImage("fgl/editor/resources/img16/file.png")));
        menuItem.setActionCommand("Agile");
        menuItem.addActionListener(this);
        submenu.add(menuItem);

        submenu.add(menuItem);
        this.popup.add(submenu);
        this.popup.addSeparator();       

        menuItem = new JMenuItem("Rename", new ImageIcon(Util.getIconImage("fgl/editor/resources/img16/rename.png")));
        menuItem.setActionCommand("Rename");
        menuItem.addActionListener(this);
        this.popup.add(menuItem);
        this.popup.addSeparator();

        menuItem = new JMenuItem("Delete", new ImageIcon(Util.getIconImage("fgl/editor/resources/img16/delete.png")));
        menuItem.setActionCommand("Delete");
        menuItem.addActionListener(this);
        this.popup.add(menuItem);
    }

    public void addPopupFile() {
        this.popup.removeAll();

        JMenuItem menuItem = new JMenuItem("Rename", new ImageIcon(Util.getIconImage("fgl/editor/resources/img16/rename.png")));
        menuItem.setActionCommand("Rename");
        menuItem.addActionListener(this);
        this.popup.add(menuItem);
        this.popup.addSeparator();

        menuItem = new JMenuItem("Delete", new ImageIcon(Util.getIconImage("fgl/editor/resources/img16/delete.png")));
        menuItem.setActionCommand("Delete");
        menuItem.addActionListener(this);
        this.popup.add(menuItem);
    }

    private JMenuItem getMenuItem(String s, ActionListener al) {
        JMenuItem menuItem = new JMenuItem(s);
        menuItem.setActionCommand(s.toUpperCase());
        menuItem.addActionListener(al);
        return menuItem;
    }

    public void actionPerformed(ActionEvent e) {
        String ac = e.getActionCommand();
        TreePath path = tree.getPathForLocation(loc.x, loc.y);
        if (ac.equals("NewFolder")) {
            addNewFolder(path);
        }
        if (ac.equals("Agile")) {
            addNewFile(ac, path);
        }        
        if (ac.equals("Rename")) {
            rename(path);
        }
        if (ac.equals("Delete")) {
            remove(path);
        }
    }

    private void addNewFolder(TreePath path) {
        System.out.println("TreePath : " + path);
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getLastPathComponent();
        System.out.println("parent : " + parent);

        DlgNewFolder dialog = new DlgNewFolder();
        dialog.setVisible(true);
        File folder = new File(parent + File.separator + dialog.getName());
        if (!folder.exists()) {
            folder.mkdirs();
            System.out.println("createDirectory : " + folder.getAbsolutePath());
        }

        this.tree.reload();
    }

    private void addNewFile(String type, TreePath path) {
        System.out.println("TreePath : " + path);
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getLastPathComponent();
        System.out.println("parent : " + parent);
        DlgNewFile dialog = new DlgNewFile();
        dialog.setVisible(true);
        File folder = new File(parent + File.separator + dialog.getName() + ".agile");
        if (!folder.exists()) {
            try {
                folder.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(PopupTree.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("createDirectory : " + folder.getAbsolutePath());
        }

        this.tree.reload();

    }

    private void rename(TreePath path) {
        // File (or directory) with old name
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getLastPathComponent();
        File file = new File(parent.toString());

        // File (or directory) with new name
        DlgRenameFile dialog = new DlgRenameFile();
        dialog.setVisible(true);
        this.tree.rename_to_tab(parent.toString(),dialog.getName());
        File file2;
        if (file.isFile()) {
            file2 = new File(file.getParent() + File.separator + dialog.getName() + ".agile");
        } else {
            file2 = new File(file.getParent() + File.separator + dialog.getName());
        }

        // Rename file (or directory)
        boolean success = file.renameTo(file2);
        this.tree.reload();
        if (!success) {
            this.tree.reload();
        }
        


    }

    private void remove(TreePath path) {
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) path.getLastPathComponent();
        File file = new File(parent.toString());
        if (file.isFile()) {
            boolean success = file.delete();
            if (!success) {
                System.out.println("Deletion failed." + parent.toString());
            } else {
                System.out.println("File deleted." + parent.toString());
            }
        } else {
            delete(parent.toString(), true);
        }

        this.tree.reload();
    }

    public boolean delete(String filePath, boolean recursive) {
        File file = new File(filePath);
        if (!file.exists()) {
            return true;
        }

        if (!recursive || !file.isDirectory()) {
            return file.delete();
        }

        String[] list = file.list();
        for (int i = 0; i < list.length; i++) {
            if (!delete(filePath + File.separator + list[i], true)) {
                return false;
            }
        }

        return file.delete();
    }

    private void addChild(TreePath path) {
        DefaultMutableTreeNode parent =
                (DefaultMutableTreeNode) path.getLastPathComponent();
        int count = parent.getChildCount();
        DefaultMutableTreeNode child =
                new DefaultMutableTreeNode("child " + count);
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        model.insertNodeInto(child, parent, count);

    }

    private void addSibling(TreePath path) {
        DefaultMutableTreeNode node =
                (DefaultMutableTreeNode) path.getLastPathComponent();
        DefaultMutableTreeNode parent =
                (DefaultMutableTreeNode) node.getParent();
        int count = parent.getChildCount();
        DefaultMutableTreeNode child =
                new DefaultMutableTreeNode("child " + count);
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        model.insertNodeInto(child, parent, count);
    }
}
